package com.pickgliss.light2d.texture
{
	import com.pickgliss.ds.BitmapLib;
	import com.pickgliss.light2d.display.LightStage;
	import com.pickgliss.loaders.ActionInfo;
	
	import flash.display3D.VertexBuffer3D;
	import flash.geom.Matrix3D;
	import flash.geom.Point;
	import flash.geom.Rectangle;

	public class SpriteTexture extends ImageTexture
	{
		public function SpriteTexture()
		{
			_defaultMatrix = new Matrix3D();
			super();
		}
		
		private var _actionInfos:Vector.<ActionInfo>;
		private var _currentAction:ActionInfo;
		private var _currentFrame:int = 0;
		
		override public function step():void
		{
			if(_actionInfos == null)
			{
				_actionInfos = BitmapLib.Instance.getActions(_textureId);
				_currentAction = _actionInfos[0];
			}
			if(_actionInfos != null)
			{
				_currentFrame ++;
				if(_currentFrame >= _currentAction.frameRects.length)_currentFrame = 0;
			}
		}
		
		override public function getDefaultMatrix():Matrix3D
		{
			var currentRect:Rectangle = _currentAction.frameRects[_currentFrame];
			var currentRegsterPoint:Point = _currentAction.centerPos[_currentFrame];
			_defaultMatrix.identity();
			_defaultMatrix.appendScale(currentRect.width/2,currentRect.height/2,1);
			_defaultMatrix.appendTranslation(currentRegsterPoint.x,currentRegsterPoint.y,0);
			return _defaultMatrix;
		}
		private var _uvBuffer:VertexBuffer3D;
		
		override public function getUVBuffer():VertexBuffer3D
		{
			var currentRect:Rectangle = _currentAction.frameRects[_currentFrame];
			_uvBuffer = LightStage.context3D.createVertexBuffer(4, 2);
			var vertextes:Vector.<Number>=Vector.<Number>([ currentRect.x/textureWidth, currentRect.y/textureHeight, 
				(currentRect.x+currentRect.width)/textureWidth, currentRect.y/textureHeight,
				(currentRect.x+currentRect.width)/textureWidth, (currentRect.y+currentRect.height)/textureHeight,
				currentRect.x/textureWidth, (currentRect.y+currentRect.height)/textureHeight]);
			_uvBuffer.uploadFromVector(vertextes, 0, 4);
			return _uvBuffer;
		}
	}
}